"""将测试结果返回给测试平台
"""

import os
import time
import json
import requests
import constant
from utils.utils_log import loggerCase



def return_result():
    """
    将测试结果返回给测试平台
    """
    loggerCase.info("测试结果返回测试平台开始")
    with open(constant.result_json_Path, 'r', encoding="utf-8") as f:
        test_result = json.load(f)
    loggerCase.info(f"测试结果{test_result}")
    loggerCase.info(requests.post(url=constant.TEST_PLATFORM_PATH, json=test_result).text)
    loggerCase.info("测试结果返回测试平台结束")



def rename_json(*args):
    """
    将testcase_result.json重命名
    """
    loggerCase.info("testcase_result.json重命名开始")
    try:
        for old_result_path in args:
            path, name = os.path.split(old_result_path)
            now_time = time.strftime(f"%Y_%m_%d_%H_%M", time.localtime(time.time()))
            new_result_path = path + '/' + now_time + '_' + name
            if not os.path.exists(new_result_path) and os.path.exists(old_result_path):
                os.rename(old_result_path, new_result_path)
            else:
                loggerCase.info(f'{new_result_path}已存在！！！')
    except:
        pass
    finally:
        loggerCase.info("testcase_result.json重命名级结束")


def remove_path(remove_path_list):
    """
    将remove_path_list中的文件删除
    """
    loggerCase.info("remove_path_list中的文件删除开始")
    for i in remove_path_list:
        if os.path.exists(i):
            os.remove(i)
        else:
            loggerCase.info(f'{i}不存在！！！')
    loggerCase.info("remove_path_list中的文件删除结束")


# def modify_redis():
#     """
#     修改redis为0
#     """
#     try:
#         with open(readconfig.taskIdPath, 'r') as f:
#             task_id = f.readline()
#     except:
#         task_id = 'loca'
#     FactoryRedis.dlp_flag.delt(f"name_{task_id}")


def teardown():
    """
    执行teardown
    """
    loggerCase.info('teardown开始')
    # log().info('teardown开始')
    # modify_redis()
    return_result()

    old_result_path_json_1 = constant.result_json_Path
    rename_json(old_result_path_json_1)

    remove_path_list = [constant.taskId_path, constant.time_json_path, constant.result_json_Path]
    remove_path(remove_path_list)

    # analysis_main()
    loggerCase.info("teardown结束")


if __name__ == '__main__':
    # with open(readconfig.resultJsonPath, 'r',encoding="utf-8") as f:
    #     test_result = json.load(f)
    # sout_file = readconfig.resultJsonPath
    # path, name = os.path.split(sout_file)
    # now_time = time.strftime(f"%Y_%m_%d_%H_%M", time.localtime(time.time()))
    # new_result_path = path + '/' + now_time + '_' + name
    # os.chdir(path)
    # with open(file=new_result_path,mode='w') as filea:
    #     filea.write(json.dumps(test_result))
    teardown()
